package com.kk.test.connectionpool;


import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;

public class ConnectionPoolImpl implements IConnectionPool, DataSource {
    /**
     * 连接池中连接数(计数器)
     */
    AtomicInteger connectionCount = new AtomicInteger(0);

    private DataSourceConfig dataSourceConfig;

    /**
     * 声明一个线程安全的集合，存储空闲的连接
     * ArrayList线程不安全
     * Vector线程安全
     */
    Vector<Connection> freePools = new Vector<>();

    /**
     * 声明一个线程安全的集合，存储正在使用的连接对象
     * ArrayList线程不安全
     * Vector线程安全
     */
    Vector<ConnectionEntity> usePools = new Vector<>();


    public ConnectionPoolImpl(DataSourceConfig dataSourceConfig) {
        this.dataSourceConfig = dataSourceConfig;
        //初始化连接池
        init();
    }

    /**
     * 连接池的初始化
     */
    private void init() {
        for (int i = 0; i < Integer.valueOf(dataSourceConfig.getInitialSize()); i++) {
            Connection connection = createConnection();
            System.out.println("连接池初始化，连接对象：" + connection);
            freePools.add(connection);
        }
        //启动健康检查,防止连接池连接对象是否超时 导致一直不释放
        if (Boolean.valueOf(dataSourceConfig.getHealth()) == true) {
            checkConnectionTimeOut();
        }
    }

    /**
     * 定时检查占用时间超长的连接，并关闭
     */
    private void checkConnectionTimeOut() {
        Worker worker = new Worker();
        //调度任务，延迟delay毫秒后执行，period毫秒执行一次
        new Timer().schedule(worker, Long.valueOf(dataSourceConfig.getDelay()), Long.valueOf(dataSourceConfig.getPeriod()));
    }

    class Worker extends TimerTask {
        @Override
        public void run() {
            //System.out.println("定时检查占用时间超长的连接Connection并关闭...");
            //遍历正在使用的连接对象
            try {
                Iterator<ConnectionEntity> iterator = usePools.iterator();
                while (iterator.hasNext()){
                    ConnectionEntity connectionEntity = iterator.next();
                    if (System.currentTimeMillis() - connectionEntity.getUseStartTime() > Long.valueOf(dataSourceConfig.getTimeout())) {
                        Connection connection = connectionEntity.getConnection();
                            connection.close();
                            iterator.remove();
                            // 连接数减1
                            connectionCount.decrementAndGet();
                            if (connectionCount.get() < Integer.valueOf(dataSourceConfig.getInitialSize())) {
                                System.out.println("连接对象" + connection + "超时关闭！");
                                System.out.println("因销毁导致空闲连接数过小，进行补充...");
                                Connection newConnection = createConnection();
                                freePools.add(newConnection);
                            }
                            System.out.println("空闲连接池大小是：" + freePools.size() + "，正在使用的连接池大小是" + usePools.size() + ",总连接数：" + connectionCount);

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建连接池
     *
     * @return
     */
    public synchronized Connection createConnection() {
        Connection connection = null;
        try {
            Class.forName(dataSourceConfig.getDriverClassName());
            connection = DriverManager.getConnection(dataSourceConfig.getUrl(), dataSourceConfig.getUsername(), dataSourceConfig.getPassword());
            //连接数加1
            connectionCount.incrementAndGet();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 从连接池获取连接对象
     *
     * @return
     */
    @Override
    public synchronized Connection getConn() {
        Connection connection = null;
        try {
            //判断连接池是否为空
            if (!freePools.isEmpty()) {
                connection = freePools.get(0);
                if (isAvailable(connection)) {
                    freePools.remove(connection);
                    ConnectionEntity connectionEntity = new ConnectionEntity(connection, System.currentTimeMillis());
                    usePools.add(connectionEntity);
                }
                System.out.println(Thread.currentThread().getName() + "从连接池获取连接对象：" + connection + ",空闲连接池大小是：" + freePools.size() + ",正在使用的连接池大小是" + usePools.size() + ",总连接数：" + connectionCount);
            } else {
                // 空闲连接池为空,新创建连接
                if (connectionCount.get() < Integer.valueOf(dataSourceConfig.getMaxSize())) {
                    connection = createConnection();
                    ConnectionEntity connectionEntity = new ConnectionEntity(connection, System.currentTimeMillis());
                    usePools.add(connectionEntity);
                    System.out.println(Thread.currentThread().getName() + "连接池没有空闲连接，创建一个新的：" + connection + ",空闲连接池大小是：" + freePools.size() + ",正在使用的连接池大小是" + usePools.size() + ",总连接数：" + connectionCount);
                } else {
                    //连接池已满
                    System.out.println(Thread.currentThread().getName() + "连接池已满，继续等待！" + ",空闲连接池大小是：" + freePools.size() + ",正在使用的连接池大小是" + usePools.size() + ",总连接数：" + connectionCount);

                    this.wait(Integer.valueOf(dataSourceConfig.getWaittime()));
                    //获取连接对象的重试
                    connection = getConn();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 判断连接对象是否可用
     *
     * @param connection
     * @return
     */
    private boolean isAvailable(Connection connection) {
        try {
            if (connection != null && !connection.isClosed()) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public synchronized void releaseConn(Connection connection) {
        if (isAvailable(connection)) {
            freePools.add(connection);
            for (int i = 0; i < usePools.size(); i++) {
                if (usePools.get(i).getConnection().equals(connection)) {
                    usePools.remove(i);
                    break;
                }
            }
            System.out.println(Thread.currentThread().getName() + "归还了一个连接对象：" + connection + ",空闲连接池大小是：" + freePools.size() + ",正在使用的连接池大小是" + usePools.size() + ",总连接数：" + connectionCount);
        }
        this.notifyAll();
    }


    @Override
    public Connection getConnection() throws SQLException {
        // 调用你自己实现的 getConn 方法
        return getConn();
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    // 以下方法只需提供基本实现即可
    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public java.io.PrintWriter getLogWriter() throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void setLogWriter(java.io.PrintWriter out) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public int getLoginTimeout() throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}

